#include "login.h"
#include "string.h"
#include <openssl/md5.h>
int signIn()
{
    char user_name[20] = {0};
    char password[20] = {0};
    while (1)
    {
        printf("账号：");
        scanf("%s", user_name);
        int i;
        for (i = 0; i < login.userNum; i++)
        {
            if (strcmp(user_name, login.user[i].userName) == 0)
            {
                while (1)
                {
                    printf("密码：");
                    scanf("%s", password);
                    if (strcmp(password, login.user[i].password) == 0)
                    {
                        printf("登录成功\n");
                        break;
                    }
                    printf("密码错误\n");
                }
                break;
            }
        }
        if (i == login.userNum)
        {
            printf("用户不存在，可以注册用户\n");
            return -1;
        }
        break;
    }
    return 0;
}

void regUser()
{
    char user_name[20] = {0};
    char password[20] = {0};
    while (1)
    {
        printf("账号：");
        scanf("%s", user_name);
        if (strlen(user_name) < 6 | strlen(password) > 19)
        {
            printf("账号不少于6个且不大于19个字符，请重新输入。\n");
            continue;
        }
        break;
    }
    while (1)
    {
        printf("密码：");
        scanf("%s", password);
        if (strlen(password) < 6 | strlen(password) > 19)
        {
            printf("密码不少于6个且不大于19个字符，请重新输入。\n");
            continue;
        }
        break;
    }
    memcpy(login.user[login.userNum].userName, user_name, strlen(user_name));
    memcpy(login.user[login.userNum].password, password, strlen(password));
    login.userNum++;
    logWriteToFile();
}

int logWriteToFile()
{
    FILE *f = fopen(FILENAME, "w+");
    if (f == NULL)
    {
        printf("打开文件失败！\n");
        return -1;
    }
    for (int i = 0; i < login.userNum; i++)
    {
        fprintf(f, "%s %s\n", login.user[i].userName, login.user[i].password);
        fflush(f);
    }
    return 0;
}
int logReadFromFile()
{
    FILE *f = fopen(FILENAME, "r");
    if (f == NULL)
    {
        printf("打开文件失败！\n");
        return -1;
    }
    while (fscanf(f, "%s %s\n", login.user[login.userNum].userName, login.user[login.userNum].password) != EOF)
    {
        login.userNum++;
    }
    return 0;
}